AidMe = {}

local version = "0.1.0"

local isAidMeRunning
local assistTarget = ""
local currentTargetId
local currentTargetName = ""

function AidMe.Initialize()
  AidMe.Disable()

  LibSlash.RegisterSlashCmd("AidMe", AidMe.HandleSlashCommand)	
  
  RegisterEventHandler(SystemData.Events.PLAYER_TARGET_UPDATED, "AidMe.OnPlayerTargetUpdated")
end

function AidMe.OnPlayerTargetUpdated(targetClassification, targetId, targetType)
  if (AidMe.currentTargetId ~= targetId) then
    AidMe.currentTargetId = targetId
    AidMe.currentTargetName = WStringToString(TargetInfo:UnitName(targetClassification))
  end
end

function AidMe.parseArguments(delimiter,str)
  if (delimiter=='') then 
    return false 
  end
  
  local pos = 0
  local arr = {}
  for st,sp in function() return string.find(str,delimiter,pos,true) end do
    table.insert(arr,string.sub(str,pos,st-1)) 
    pos = sp + 1
  end
  table.insert(arr,string.sub(str,pos))
  return arr
end

function AidMe.HandleSlashCommand(input)
  local args = AidMe.parseArguments(" ",input)
  if args[1] == "help" then
    AidMe.DisplayHelp();
  elseif args[1] == "on" then
    AidMe.Enable()
  elseif args[1] == "off" then
    AidMe.Disable()
  elseif args[1] == "status" then
    AidMe.DisplayStatus()
  elseif args[1] == "target" then
    AidMe.SetAssistTarget(args[2])
  elseif args[1] == "assist" then
    AidMe.Assist(assistTarget)
  else
    AidMe.DisplayHelp();
  end  
end

function AidMe.DisplayHelp()
  AidMe.WriteToChat("AidMe addon Help")
  AidMe.WriteToChat("Version: "..version)
  AidMe.DisplayStatus()
  AidMe.WriteToChat("Usage: /aidme [arguments]")
  AidMe.WriteToChat("/aidme help - display this help message")
  AidMe.WriteToChat("/aidme [on/off] - turn the AidMe addon on/off")
  AidMe.WriteToChat("/aidme status - display the current status for AidMe")
  AidMe.WriteToChat("/aidme target [PC] - set AidMe to assist the provided Player Character (PC)")
  AidMe.WriteToChat("/aidme assist - assist the PC set within AidMe")
end

function AidMe.Enable()
  isAidMeRunning = true
  AidMe.WriteToChat("AidMe addon is enabled")
end

function AidMe.Disable()
  isAidMeRunning = false
  AidMe.WriteToChat("AidMe addon is disabled")
end

function AidMe.DisplayStatus()
  if isAidMeRunning then
    AidMe.WriteToChat("Status: AidMe enabled")
  else 
    AidMe.WriteToChat("Status: AidMe disabled")
  end
  AidMe.WriteToChat(L"Target: "..towstring(assistTarget))
end

function AidMe.Assist(target)
  SystemData.UserInput.ChatText = L"/assist "..target
  BroadcastEvent( SystemData.Events.SEND_CHAT_TEXT )
end

function AidMe.SetAssistToCurrentTarget()
	AidMe.SetAssistTarget(currentTargetName)
end

function AidMe.SetAssistTarget(target)
  assistTarget = towstring(target)
  AidMe.WriteToChat(L"AidMe: Assisting '"..assistTarget..L"'")
end

function AidMe.WriteToChat(text)
  EA_ChatWindow.Print(towstring(text))
end
